// Package main.
// creator 2022-02-25 02:13:50
// Author  zhenxinma.
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"gitee.com/zhenxinma/go_base/internal/network/udp"
	"math/big"
	"time"
)

const Addr = "localhost:9999"

func main() {
	go runServer()
	time.Sleep(1 * time.Second)
	go runClient()
	time.Sleep(4 * time.Minute)
}

func runServer() {
	server := udp.NewUdpServer(Addr)
	server.Run(generateTLSConfig())
}

func runClient() {

	client := udp.NewClient(Addr)
	client.SendMessage([]byte("Hello Word"))
}

func generateTLSConfig() *tls.Config {

	//key, err := rsa.GenerateKey(rand.Reader, 1024)
	//if err != nil {
	//	panic(err)
	//}
	//template := x509.Certificate{SerialNumber: big.NewInt(1)}
	//certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	//if err != nil {
	//	panic(err)
	//}
	//keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	//certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
	//
	//tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	//if err != nil {
	//	panic(err)
	//}
	//return &tls.Config{Certificates: []tls.Certificate{tlsCert}}
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}
	template := x509.Certificate{SerialNumber: big.NewInt(1)}
	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	if err != nil {
		panic(err)
	}
	return &tls.Config{
		Certificates: []tls.Certificate{tlsCert},
		NextProtos:   []string{"quic-echo-example"},
	}
}
